using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.IO;
using CYZHAPI.Common;
using CYZHAPI.Entity;
using CYZHAPI.IRepository.IService;
using CYZHAPI.Middlewares;

using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using CYZHAPI.web.Model;
using Microsoft.Extensions.Options;
using CYZHAPI.Common.Config;
using Microsoft.Net.Http.Headers;
using Microsoft.AspNetCore.Http;
using CYZHAPI.Common.tools;
namespace CYZHAPI.web.Controllers
{
    //[Route("api/[controller]")]
    //[EnableCors(WebApiOption.CORS_POLICY_NAME)] //设置跨域处理的 代理
    public class ascController : BaseController
    {
         private IHttpContextAccessor _accessor;
        private WebApiOption _Config;
        private IAscService _ascService;
        public ascController(IHttpContextAccessor accessor,IOptions<WebApiOption> option,IAscService ascService, ILogger<BaseController> logger) : base(logger)
        {
             _accessor = accessor;
              _Config = option.Value;
            _ascService = ascService;
        }

        // GET api/values
        [HttpGet]
        public AscRenBean Get(AscSeachBean value)
        {
            value.dataformat = value.dataformat == null ? "" : value.dataformat;
            value.scope = value.scope == null ? "" : value.scope;
            value.fileName = value.fileName == null ? "" : value.fileName;
            value.beginTime = value.beginTime == null ? "" : value.beginTime;
            value.endTime = value.endTime == null ? "" : value.endTime;
            string sWhere = "";
            if(!value.dataformat.Equals("")){
                sWhere += sWhere.Equals("") ? "DATAFORMAT = '"+value.dataformat+"'" : " and DATAFORMAT = '"+value.dataformat+"'";
            }

            if(!value.scope.Equals("")){
                sWhere += sWhere.Equals("") ? "SCOPE = '"+value.scope+"'" : " and SCOPE = '"+value.scope+"'";
            }

            if(!value.fileName.Equals("")){
                sWhere += sWhere.Equals("") ? "FILENAME like '%"+value.fileName+"%'" : " and FILENAME like '%"+value.fileName+"%'";
            }

            if(!value.beginTime.Equals("")){
                //DateTime BTime = Convert.ToDateTime(value.beginTime);
                sWhere += sWhere.Equals("") ? "FILEDATATIME > to_date('"+value.beginTime+"','yyyy-mm-dd')" : " and FILEDATATIME > to_date('"+value.beginTime+"','yyyy-mm-dd')";
            }

            if(!value.endTime.Equals("")){
                sWhere += sWhere.Equals("") ? "FILEDATATIME < to_date('"+value.endTime+"','yyyy-mm-dd')" : " and FILEDATATIME < to_date('"+value.endTime+"','yyyy-mm-dd')";
            }

            List<AscModel> ListInfo = _ascService.GetList(sWhere);
            AscRenBean renBean = new AscRenBean();
            if(ListInfo != null){
                renBean.code = "200";
                renBean.message = "气象数据查询成功";
                renBean.reList = ListInfo;
            }else{
                renBean.code = "901";
                renBean.message = "气象数据查询失败";
                renBean.reList = null;
            }

            return renBean;
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public AscRenBean Get(string id)
        {
            id = id == null ? "" : id;
            AscRenBean renBean = new AscRenBean();
            if(id.Equals("")){
                renBean.code = "901";
                renBean.message = "气象数据查询失败";
                renBean.reList = null;
                return renBean;
            }
            string sWhere = "id = "+id;
            List<AscModel> ListInfo = _ascService.GetList(sWhere);
            
            if(ListInfo != null){
                renBean.code = "200";
                renBean.message = "气象数据查询成功";
                renBean.reList = ListInfo;
            }else{
                renBean.code = "901";
                renBean.message = "气象数据查询失败";
                renBean.reList = null;
            }

            return renBean;
        }

        [Route("Seach")]
        [HttpPost]
        public AscRenBean Seach([FromBody]AscSeachBean value)
        {
            //AscSeachBean value = new AscSeachBean();
            value.dataformat = value.dataformat == null ? "" : value.dataformat;
            value.scope = value.scope == null ? "" : value.scope;
            value.fileName = value.fileName == null ? "" : value.fileName;
            value.beginTime = value.beginTime == null ? "" : value.beginTime;
            value.endTime = value.endTime == null ? "" : value.endTime;
            string sWhere = "";
            if(!value.dataformat.Equals("")){
                sWhere += sWhere.Equals("") ? "DATAFORMAT = '"+value.dataformat+"'" : " and DATAFORMAT = '"+value.dataformat+"'";
            }

            if(!value.scope.Equals("")){
                sWhere += sWhere.Equals("") ? "SCOPE = '"+value.scope+"'" : " and SCOPE = '"+value.scope+"'";
            }

            if(!value.fileName.Equals("")){
                //sWhere += sWhere.Equals("") ? "FILENAME = '"+value.fileName+"'" : " and FILENAME = '"+value.fileName+"'";
                sWhere += sWhere.Equals("") ? "FILENAME like '%"+value.fileName+"%'" : " and FILENAME like '%"+value.fileName+"%'";
            }

            if(!value.beginTime.Equals("")){
                //DateTime BTime = Convert.ToDateTime(value.beginTime);
                sWhere += sWhere.Equals("") ? "FILEDATATIME >= to_date('"+value.beginTime+"','yyyy-mm-dd')" : " and FILEDATATIME >= to_date('"+value.beginTime+"','yyyy-mm-dd')";
            }

            if(!value.endTime.Equals("")){
                sWhere += sWhere.Equals("") ? "FILEDATATIME <= to_date('"+value.endTime+"','yyyy-mm-dd')" : " and FILEDATATIME <= to_date('"+value.endTime+"','yyyy-mm-dd')";
            }
            if(sWhere.Equals("")){
                sWhere +="id>0";
            }
            List<AscModel> ListInfo = _ascService.GetList(sWhere);
            AscRenBean renBean = new AscRenBean();
            if(ListInfo != null){
                renBean.code = "200";
                renBean.message = "气象数据查询成功";
                renBean.reList = ListInfo;
            }else{
                renBean.code = "901";
                renBean.message = "气象数据查询失败";
                renBean.reList = null;
            }
            

            return renBean;
        }

        [Route("Post")]
        // POST api/values
        [HttpPost]
        public BaseResponseResult Post([FromBody]List<AscModel> value)
        {
            BaseResponseResult response = new BaseResponseResult();
            bool e = _ascService.insert("ASC_DATA_DIRECTORIES",value);
            if(e){
                response = new BaseResponseResult
                {
                    code = "200",
                    message = "数据库插入成功!"
                };
            }else{
                response = new BaseResponseResult
                {
                    code = "901",
                    message = "数据库插入错误!"
                };
            }
            
            return response;
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public BaseResponseResult Put(long id, [FromBody]AscModel value)
        {
            BaseResponseResult response = new BaseResponseResult();
            bool e = _ascService.update(id,value);//"ASC_DATA_DIRECTORIES"
            if(e){
                response = new BaseResponseResult
                {
                    code = "200",
                    message = "数据更新成功!"
                };
            }else{
                response = new BaseResponseResult
                {
                    code = "901",
                    message = "数据更新错误!"
                };
            }

            return response;
        }

        // DELETE api/values/5
       // [HttpDelete("{id}")]
        [Route("Delete")]
        [HttpGet("{id}")]
        public BaseResponseResult Delete(int id)
        {
           // id = id == null ? "" : id;
           // var sid=Convert.ToInt32(id);
            BaseResponseResult response = new BaseResponseResult();
            bool e = _ascService.Delete(id);//"ASC_DATA_DIRECTORIES"
            if(e){
                response = new BaseResponseResult
                {
                    code = "200",
                    message = "数据删除成功!"
                };
            }else{
                response = new BaseResponseResult
                {
                    code = "901",
                    message = "数据删除错误!"
                };
            }
            return response;
        }
        [Route("downLoadFile")]
        [HttpGet]
        public async Task<IActionResult> downLoadFile(string fileid){
            
            var sWhere="id="+fileid;
            var path=_Config.Path.AscSource;
            List<AscModel> ListInfo = _ascService.GetList(sWhere);
            if(ListInfo != null&&ListInfo.Count==1){
                AscModel srm=ListInfo[0];
                
                 var addrUrl=path+"\\"+srm.id+".asc";
                var stream = System.IO.File.OpenRead(addrUrl);
                return File(stream, "application/octet-stream", srm.filename+".asc");
            }else{
                return null;
            }
           
        }
        [Route("UploadFile")]
        [HttpPost]
        public AscRenBean UploadFile(){
            HttpContext context = _accessor.HttpContext;
            //string filetype = _accessor.HttpContext.Request.Form["filetype"];
           // string filetime = _accessor.HttpContext.Request.Form["filetime"];
            IFormFileCollection obj_Files = _accessor.HttpContext.Request.Form.Files;
           
            if(obj_Files.Count == 0 ) 
                return  new AscRenBean(){
                        code = "901",
                        message = "缺少上传的文件"
                    };
            List<AscModel> ListInfo =new List<AscModel>();
            for(int i = 0; i<obj_Files.Count; i++)
            {
                
                IFormFile upload_file = obj_Files[i];
                // 文件大小
                long size = 0;
                // 原文件名（包括路径）
                var filename = ContentDispositionHeaderValue.Parse (upload_file.ContentDisposition).FileName.
                    ToString().Replace ("\"", "");
                // 扩展名
                //var extName = filename.Substring (filename.LastIndexOf ('.')).Replace ("\"", "");
                // 新文件名
                //string shortfilename = "test" + extName;
                // 新文件名（包括路径）_hostingEnvironment.WebRootPath 
                //string sfilepath = EntityKeyToValue.getProperties<PathOption>(_Config.Path,filetype) + @"\"+filetime;
                var path=_Config.Path.AscSource;
               // decimal id= _ascService.degetNextSecquece("ASC_DATA_SEQUENCE");
                string id="9999";
                string file_name = path + @"\" + id+".asc";

                string extfileName = Path.GetFileNameWithoutExtension(filename);
                string[] rqs = extfileName.Split('-');
                DateTime dt = DateTime.ParseExact(rqs[1], "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
                // 设置文件大小
                //size += upload_file.Length;
                // 创建新文件
                try
                {
                    if(Directory.Exists(path) == false)//如果不存在就创建file文件夹
                    {
                        Directory.CreateDirectory(path);
                    }
                    //Directory.Delete(Server.MapPath("~/upimg/hufu"), true);//删除文件夹以及文件夹中的子目录，文件    
                    //判断文件的存在
                    if (System.IO.File.Exists(file_name))
                    {
                        //文件存在删除文件
                        System.IO.File.Delete(file_name);
                    }
                    using (FileStream fs = System.IO.File.Create (file_name))
                    {
                        // 复制文件
                        upload_file.CopyTo (fs);
                        // 清空缓冲区数据
                        fs.Flush ();
                    }
                    AscModel am=new AscModel(){
                        id = Convert.ToInt32(id),
                        scope = "全国",
                        dataformat = "asc",
                        filename =extfileName ,
                        createtime = DateTime.Now,
                        createby = "wyf",
                        updatetime = DateTime.Now,
                        updateby = "wyf",
                        filedatatime = dt
                    };
                    ListInfo.Add(am);


                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    return  new AscRenBean(){
                        code = "901",
                        message = "文件上传错误，无法保存"
                    };
                }
            }
           // bool isSuccess = _ascService.insert("ASC_DATA_DIRECTORIES",ListInfo);
            return new AscRenBean(){
                code = "200",
                message = "文件上传成功",
                reList=ListInfo
            };
        }
        // [Route("downLoadFile")]
        // [HttpGet]
        // public BinaryRenBean downLoadFile(string fileid){
            
        //     var sWhere="id="+fileid;
        //     var path=_Config.Path.AscSource;
        //     List<AscModel> ListInfo = _ascService.GetList(sWhere);
        //     BinaryRenBean brb=new BinaryRenBean();
        //     if(ListInfo != null&&ListInfo.Count==1){
        //         AscModel srm=ListInfo[0];
                
        //          var addrUrl=path+"\\"+srm.id+".asc";
        //         var stream = System.IO.File.OpenRead(addrUrl);
        //         brb.filename= srm.filename+".asc";
        //         brb.ostream=File(stream, "application/octet-stream", srm.filename+".asc");
        //         //return File(stream, "application/octet-stream", srm.filename+".asc");
        //        return brb;
        //     }else{
        //         return brb;
        //     }
           
        // }


    }
}